﻿using System;
using System.Collections.Generic;
using System.Globalization;
using Medianamik.Core;
using Medianamik.Core.DAL;
using Medianamik.Core.DAL.Repositories;
using Medianamik.Core.DAL.Services;
using Medianamik.UI.Web.Shop.Data.Interfaces;
using SubSonic;
using System.Linq;

namespace Medianamik.UI.Web.Shop.Data.Repositories
{
    public class OrderRepository<TCollection, T, TItem> : MedianamikRepository<TCollection, T>,
        IOrderRepository<T, TItem>
        where T : IOrder<TItem>, IRecordBase, new()
        where TCollection : ICollectionWithChildren<TCollection, T>, new()
        where TItem : Interfaces.IOrderItem
    {
        public OrderRepository(ICultureService cultureService, IContentStateService contentStateService, INodeMapper nodeMapper) : base(cultureService, contentStateService, nodeMapper)
        {
        }

        public override T Get(Guid nodeId)
        {
            return Get(nodeId, CultureInfo.InvariantCulture, ContentState.Draft);
        }

        public void DeleteOrderItems(IOrder<TItem> order)
        {
            DeleteByParent(order.NodeId, true);
        }

        public T GetOrderByTransactionId(string transactionId)
        {
            var wheres = new List<Where>
                 {
                     new Where
                         {
                             ColumnName = ShopSchema.Order.Columns.TransactionId,
                             Comparison = Comparison.Equals,
                             ParameterValue = transactionId
                         }
                 };
            return GetWithFilters(CultureInfo.InvariantCulture, ContentState.Draft, ActiveStatus.All, 
                TypeIds.Order, null, wheres, null, "", null, true).FirstOrDefault();
        }
    }

    public class OrderRepository : OrderRepository<OrderCollection, Order, OrderItem>, IOrderRepository
    {
        public OrderRepository(ICultureService cultureService, IContentStateService contentStateService, INodeMapper nodeMapper)
            : base(cultureService, contentStateService, nodeMapper)
        {
        }
    }

    public interface IOrderRepository<T, TItem> : IMedianamikRepository<T>
        where T : IOrder<TItem>
        where TItem : Interfaces.IOrderItem

    {
        void DeleteOrderItems(IOrder<TItem> order);
        T GetOrderByTransactionId(string transactionId);
    }
    public interface IOrderRepository:  IOrderRepository<Order, OrderItem>
    {}

}
